/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.unicauca.opentextbook.fachadas;

import edu.unicauca.opentextbook.entidades.Libro;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.persistence.QueryTimeoutException;
import javax.persistence.TransactionRequiredException;

/**
 *
 * @author Gamificaion
 */
@Stateless
public class LibroFacade extends AbstractFacade<Libro> {
    @PersistenceContext(unitName = "openTextBookPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public LibroFacade() {
        super(Libro.class);
    }
    
    public Libro buscarLibro(int idLibro) {
        final StringBuilder sql = new StringBuilder();
        Query query;
        Libro libro = null;

        sql.append("SELECT * ");
        sql.append("FROM libro l ");
        sql.append("WHERE l.idLibro = ?");

        try {
            query = em.createNativeQuery(sql.toString(), Libro.class);
            query.setParameter(1, idLibro);

            libro = (Libro) query.getSingleResult();
        } catch (NoResultException e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ERROR_DESARROLLO_buscarLibro_NoResultException:".concat(e.getMessage()));
        } catch (NonUniqueResultException e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ERROR_DESARROLLO_buscarLibro_NonUniqueResultException:".concat(e.getMessage()));
        } catch (IllegalStateException e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ERROR_DESARROLLO_buscarLibro_IllegalStateException:".concat(e.getMessage()));
        } catch (QueryTimeoutException e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ERROR_DESARROLLO_buscarLibro_QueryTimeoutException:".concat(e.getMessage()));
        } catch (TransactionRequiredException e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ERROR_DESARROLLO_buscarLibro_TransactionRequiredException:".concat(e.getMessage()));
        } catch (PersistenceException e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ERROR_DESARROLLO_buscarLibro_PersistenceException:".concat(e.getMessage()));
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ERROR_DESARROLLO_buscarLibro_Exception:".concat(e.getMessage()));
        } finally {
            return libro;
        }
    }
    
}
